package org.KeyCrafter.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import org.KeyCrafter.server.session.ClientSession;
import static org.KeyCrafter.server.AppendOnlyFile.flushAppendOnlyFile;

/**
 * 返回回复消息
 * 重写 channelRead0方法，处理接收到的消息
 */

@ChannelHandler.Sharable
public class ReplyHandler extends SimpleChannelInboundHandler<ClientSession> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ClientSession c) throws Exception {
        // 发送消息
        if (c.hasReplyMessage()) {
            ctx.writeAndFlush(c.getReplyMessage());
            // 清空消息
            c.clearReply();
            // 释放查询缓冲区
            ReferenceCountUtil.release(c.getQueryBuf());
        }
        // do something ...
        // AOF 执行先放在这里
        ctx.channel().eventLoop().execute(()->flushAppendOnlyFile(true));
    }
}
